<template>
  <div class="main-box scroll">
    <el-collapse v-model="activeNames">
      <el-collapse-item title="" name="2" :icon="CaretRight">
        <template #title>
          <div class="collapse-title">
            <div
              :class="item.importance_key == selectAlarmType ? 'title-btn-select' : 'title-btn'"
              v-for="(item, index) in alarmStatistics"
              :key="index"
              @click="handleClickAlarm(item.importance_key)"
            >
              <div class="item-span">{{ item.importance_cn + "：" }}</div>
              <div class="item-number">{{ item.count }}</div>
            </div>
          </div>
        </template>
        <div class="top-box card">
          <div class="top-right">
            <div class="right1">
              <div
                v-for="(item, index) in alarmUCenter"
                :class="item.system_type == selectUCenter ? 'right1-itemShadow' : 'right1-item'"
                :style="{ 'border-bottom': `4px solid ${item.color}`, 'min-width': '130px' }"
                @click="handleClick(item.system_type)"
                :key="index"
              >
                <div class="item-span">
                  <div class="item-icon" :style="{ border: `4px solid ${item.color}` }"></div>
                  {{ item.system_type_cn }}
                </div>
                <div class="item-number">{{ item.count }}</div>
              </div>
            </div>
            <div class="right2 card2">
              <div class="progress-box">
                <div class="progress-item" v-for="(item, index) in workStatus" :key="index">
                  <div class="progress-title">{{ item.title }}</div>
                  <div class="progress-number" :style="{ color: item.color }">{{ item.value }}</div>
                  <el-progress
                    class="demo-progress"
                    :style="{ width: `${item.percentage}px`, 'min-width': '100px' }"
                    :percentage="100"
                    :color="item.color"
                    :show-text="false"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="top-left">
            <!-- <div class="left1 card2">
              <div
                class="left1-item"
                v-for="(item, index) in alarmStatistics"
                :key="index"
                :style="{ color: item.importance_key == selectAlarmType ? 'rgba(0, 165, 189, 1)' : '' }"
                @click="handleClickAlarm(item.importance_key)"
              >
                <div class="item-number">{{ item.count }}</div>
                <div class="item-span">{{ item.importance_cn }}</div>
              </div>
            </div> -->
            <div class="left2 card2">
              <PieChart class="pie" :color="color" :data="pieChartData" />
              <div class="pie-legend">
                <div
                  class="pie-legend-item"
                  v-for="(item, index) in pieChartData"
                  :key="index"
                  :style="{ color: item.type == selectAlarmLevel ? 'rgba(0, 165, 189, 1)' : '' }"
                  @click="handleClickLevel(item.type)"
                >
                  <div class="pie-icon" :style="{ background: item.color }"></div>
                  <div class="pie-content">{{ item.type_cn }}</div>
                  <div class="pie-number" :style="{ color: item.color }">{{ item.count }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="公告列表"
        highlight-current-row
        :columns="columns"
        :request-api="getWarningList"
        :pagination="true"
        :show-summary="false"
        :init-param="initParam"
        :indent="20"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 4, xl: 4 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" @click="goToTicketDetail(scope.selectedList)" :disabled="!(scope.selectedList.length > 0)">
            发起工单
          </el-button>
          <el-button type="primary" @click="openMark('markRef')">手动标记</el-button>
        </template>
        <!--Expand 表格操作-->
        <template #is_handled="scope">
          {{ scope.row.is_handled ? "已处置" : "未处置" }}
        </template>
        <!-- v-if="thisPermission.update" -->
        <template #operation="scope">
          <el-button type="primary" link @click="openDialog(scope.row)">详情</el-button>
        </template>
      </ProTable>
      <modalAddOrEdit ref="workOrderRef" @refresh="refresh" />
      <modalAddOrEdit ref="markRef" @refresh="refresh" />
    </div>
  </div>
</template>

<script setup lang="ts" name="noticeManagement">
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Warning } from "@/api/interface/warning24Hours";
import { getWarningList, getWorkStatus, getDistribution, getOverview, getImportance } from "@/api/modules/warning/warning24Hours";
import { onMounted, reactive, ref, watch, computed } from "vue";
// import { Download, Plus } from "@element-plus/icons-vue";
import { CaretRight } from "@element-plus/icons-vue";
import modalAddOrEdit from "@/views/warning/overview/component/modal_add_or_edit.vue";
import PieChart from "./component/pieChart.vue";
import { useRouter, useRoute } from "vue-router";

// import { useRoute } from "vue-router";
// import { useAuthStore } from "@/stores/modules/auth";
// const authStore = useAuthStore();
// const thisPermission = computed(() => authStore.permissionListGet[route.name as string] || {});
// import { ElMessage } from "element-plus";
// 获取路由实例
const route = useRoute();
const router = useRouter();
const activeNames = ref("2");
const proTable = ref<ProTableInstance>();
let selectUCenter = ref<string>("");
let selectAlarmType = ref<string>("");
let selectAlarmLevel = ref<string>("");
let alarmStatistics = ref<Warning.importance[]>([]);
const alarmUCenterColor = ref<string[]>([
  "rgba(86, 125, 242, 1)",
  "rgba(31, 182, 135, 1)",
  "rgba(250, 162, 67, 1)",
  "rgba(32, 172, 232, 1)",
  "rgba(248, 108, 76, 1)",
  "rgba(161, 124, 241, 1)"
]);
// 饼图颜色
const color = ref<string[]>(["#FF5E5E", "#FF9C38", "#FACA44", "#1F8CF2", "#1FB687", "#A17CF1", "#20C4F3"]);
// 进度条数值百分比*1.8
const colorList = ref<string[]>(["rgba(10, 202, 209, 1)", "rgba(31, 140, 242, 1)", "rgba(216, 233, 242, 1)"]);
// const colorList = reactive([
//   { color: "rgba(10, 202, 209, 1)", value: 6,  title: "已完成工单" },
//   { color: "rgba(31, 140, 242, 1)", value: 14, title: "未分类完成工单" },
//   { color: "rgba(216, 233, 242, 1)", value: 60,  title: "未发起工单" }
// ]);
const list = [
  { label: "重点关注", value: "important" },
  { label: "一般关注", value: "common" },
  { label: "未分类", value: "default" }
];

// 表格配置项
let columns = reactive<ColumnProps<Warning.ResReqWarningList>[]>([
  { type: "selection", width: 80 },
  { type: "index", label: "#", width: 80 },
  { prop: "system_type", label: "系统类型", search: { el: "select" }, width: 200 },
  { prop: "system_name", label: "系统名称", search: { el: "input" }, width: 200 },
  { prop: "importance", label: "重要程度", search: { el: "select", defaultValue: "" }, enum: list, width: 200 },
  { prop: "level_type", label: "告警等级", search: { el: "select", defaultValue: "" }, width: 200 },
  { prop: "name", label: "告警名称", search: { el: "input", label: "告警名称" }, width: 200 },
  { prop: "sid", label: "告警流水号", width: 200 },
  { prop: "source", label: "告警源", search: { el: "input", label: "告警源" }, width: 200 },
  { prop: "type", label: "告警类型", width: 200 },
  { prop: "status", label: "工单状态", search: { el: "input", label: "工单状态" }, width: 200 },
  { prop: "is_handled", label: "处置状态", search: { el: "input", label: "处置状态" }, width: 200 },
  { prop: "appearance_count", label: "发生次数", width: 200 },
  { prop: "updated_time", label: "最近发生时间", width: 250 },
  { prop: "created_time", label: "首次发生时间", width: 250 },
  { prop: "operation", label: "操作", fixed: "right", width: 100 }
]);
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
let workStatus = ref<Warning.ticketStatus[]>([]);
let alarmUCenter = ref<Warning.overview[]>([]);
const workOrderRef = ref<InstanceType<typeof modalAddOrEdit> | null>(null);
// 告警分布饼图数据
let pieChartData = ref<Warning.distribution[]>([]);
// 默认饼图
const defaultPieChartData = ref<Warning.distribution[]>([
  { type: "危急", type_cn: "危急", count: 0, color: "#FF5E5E" },
  { type: "高危", type_cn: "高危", count: 0, color: "#FF9C38" },
  { type: "中危", type_cn: "中危", count: 0, color: "#FACA44" },
  { type: "低危", type_cn: "低危", count: 0, color: "#1F8CF2" }
]);
onMounted(() => {
  _getWorkStatus(); // 工单状态
  _getDistribution(); // 告警分布饼图
  _getImportance(); // 重点关注，一般关注，未分类
  handleClickAlarm(route.query.importance as string);
  activeNames.value = "2";
  // 全量告警列表
  let systemType = "";
  if (route.name === "warning_history") {
    proTable.value!.searchInitParam.system_type = "self";
    proTable.value!.searchParam.system_type = "self";
    systemType = "self";
  }
  _getOverview(systemType); // unCenter卡片
  proTable.value?.getTableList();
});
const system_type = computed(() => proTable.value?.searchParam.system_type);
watch(
  () => system_type,
  async () => {
    if (system_type.value) {
      console.log(system_type.value);
      await _getDistribution(system_type.value);
      const levelList = pieChartData.value.map(item => {
        return { label: item.type_cn, value: item.count };
      }) as any;
      columns[5].enum = levelList;
    } else {
      columns[5].enum = [];
      await _getDistribution();
    }
  },
  { deep: true }
);
// watch(
//   () => route.query.importance,
//   () => {
//     proTable.value!.searchInitParam.importance = route.query.importance || "";
//     proTable.value!.searchParam.importance = route.query.importance || "";
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// );

const openDialog = (ref: string) => {
  if (ref == "workOrderRef") workOrderRef.value?.openDialog();
};

const goToTicketDetail = data => {
  const ids = data.map(item => item.id);
  console.log(ids);
  router.push({
    name: "ticket_detail",
    query: {
      alarm_id: ids.toString(),
      ticketType: "alarm"
    }
  });
};

const openMark = (param: string) => {
  console.log(param);
};

// 点击系统卡片筛选pie和列表
const handleClick = (type: string) => {
  selectUCenter.value = type == selectUCenter.value ? "" : type;
  proTable.value!.searchInitParam.system_type = selectUCenter.value;
  proTable.value!.searchParam.system_type = selectUCenter.value;
  _getDistribution(selectUCenter.value);
  proTable.value?.getTableList();
};
// 点击重要程度筛选
const handleClickAlarm = (key: string) => {
  activeNames.value = "";
  selectAlarmType.value = key == selectAlarmType.value ? "" : key;
  proTable.value!.searchInitParam.importance = selectAlarmType.value;
  proTable.value!.searchParam.importance = selectAlarmType.value;
  proTable.value?.getTableList();
};
// 点击告警分布饼图告警等级
const handleClickLevel = (key: string) => {
  selectAlarmLevel.value = key == selectAlarmLevel.value ? "" : key;
  proTable.value!.searchInitParam.level_type = selectAlarmLevel.value;
  proTable.value!.searchParam.level_type = selectAlarmLevel.value;
  proTable.value?.getTableList();
};
const refresh = () => {
  proTable.value?.getTableList();
};

const _getWorkStatus = async () => {
  const { data } = await getWorkStatus();
  if (data.length > 0) {
    // const total = data.reduce(function (prev, cur) {
    //   return prev + cur.value;
    // }, 0);
    workStatus.value = data.map((item, index) => {
      item.color = colorList.value[index];
      item.percentage = 300;
      // if (item.value !== 0 && item.value !== undefined) {
      //   item.percentage = Math.floor((item.value / total) * 100000) / 100;
      // } else {
      // }
      return item;
    });
  } else {
    workStatus.value = [];
  }
};

const _getDistribution = async (systemType?: string) => {
  pieChartData.value = [];
  const param = {
    system_type: systemType
  };
  const { data } = await getDistribution(param);
  if (data.length > 0) {
    pieChartData.value = data.map((item, index) => {
      item.color = color.value[index];
      return item;
    });
  } else {
    pieChartData.value = defaultPieChartData.value;
  }
};
const _getOverview = async (systemType?: string) => {
  let system_type_list = [] as any;
  const { data } = await getOverview();
  alarmUCenter.value = data.map((item, index) => {
    item.color = alarmUCenterColor.value[index];
    return item;
  });
  if (systemType == "self") {
    system_type_list = [{ label: "综合运管平台", value: "self" }];
  } else {
    system_type_list = data.map(item => {
      return { label: item.system_type_cn, value: item.system_type };
    }) as any;
  }
  columns[2].enum = system_type_list;
  columns[2].search = { el: "select", defaultValue: system_type_list[0]?.value };
};

const _getImportance = async () => {
  const { data } = await getImportance();
  alarmStatistics.value = data;
};
</script>

<style lang="scss" scoped>
:deep().table-search {
  padding: 18px 18px 0;
  margin-bottom: 0;
  border-bottom: 1px dashed var(--el-border-color);
  border-radius: 0;
}
:deep().table-box {
  width: 100%;
}
:deep().table-main {
  border-radius: 0;
}
:deep() .el-collapse {
  border: none;
}
:deep().el-collapse-item__header.is-active {
  background: var(--el-bg-color);
}
:deep().el-collapse-item__header {
  height: 60px;
  background: var(--el-bg-color);
}
:deep().el-collapse-item__content {
  padding-bottom: 0;
}
.main-box {
  flex-direction: column;
  height: 100%;
  &-left {
    display: flex;
    width: 250px;
    margin-right: 10px;
    border-radius: 4px;
  }
  &-main {
    display: flex;
    flex: 1;
    flex-direction: column;
    height: 100%;
  }
}
.collapse-title {
  display: flex;
  padding: 10px;
  margin-left: 10px;
  .title-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    padding: 5px 10px;
    margin-right: 10px;
    font-size: 14px;
    cursor: pointer;
    border: 1px solid var(--el-border-color);
    .item-number {
      font-weight: 700;
      color: rgb(31 140 242 / 100%);
    }
  }
  .title-btn-select {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 20px;
    padding: 5px;
    margin-right: 10px;
    font-size: 14px;
    cursor: pointer;
    background-color: var(--el-menu-active-bg-color) !important;
    border: 1px solid var(--el-border-color);
    .item-number {
      font-weight: 700;
      color: rgb(31 140 242 / 100%);
    }
  }
}
.linkCls {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  vertical-align: middle;
  cursor: pointer;
}
.top-box {
  display: flex;
  height: 352px;
  padding: 5px 20px 0;
  margin-bottom: 10px;
  border-radius: 0;
}
.top-left {
  width: 440px;
  height: 308px;
  margin-left: 24px;
  .left1 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 120px;
    padding: 0 24px;
    margin-bottom: 24px;
    border-radius: 16px;
    .left1-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      .item-number {
        font-size: 24px;
        font-weight: 700;
      }
      .item-span {
        font-size: 14px;
      }
    }
  }
  .left2 {
    display: flex;
    width: 100%;
    height: 100%;
    padding: 0;
    border-radius: 16px;
    .pie {
      width: 160px;
      height: 100%;
    }
    .pie-legend {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 180px;
      height: 100%;
    }
    .pie-legend-item {
      position: relative;
      display: flex;
      align-items: flex-end;
      width: 90%;
      height: 24px;
      padding: 2px 0;
      cursor: pointer;
    }
    .pie-icon {
      position: absolute;
      bottom: 13px;
      left: 10px;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      opacity: 1;
    }
    .pie-content {
      position: absolute;
      left: 30px;
      font-size: 14px;
    }
    .pie-number {
      position: absolute;
      right: 10px;
      font-size: 16px;
      font-weight: 500;
    }
  }
}
.top-right {
  display: flex;
  flex-direction: column;
  width: -webkit-fill-available;
  height: 308px;
  .right1 {
    display: flex;
    width: 100%;
    height: 120px;
    margin-bottom: 24px;
    .item-span {
      position: absolute;
      top: 20px;
      left: 24px;
      display: inline-flex;
      align-items: center;
      width: 60%;
      margin-bottom: 10px;
    }
    .item-number {
      position: absolute;
      top: 45px;
      left: 45px;
      font-size: 30px;
      font-weight: 700;
    }
    .item-icon {
      width: 6px;
      height: 6px;
      margin-right: 10px;
      border-radius: 50%;
      opacity: 1;
    }
  }
  .right2 {
    display: flex;
    flex: 1;
    justify-content: center;
    width: 100%;
    height: 164px;
    border-radius: 16px;
  }
}
.progress-box {
  display: flex;
  justify-content: center;
  .progress-title {
    font-size: 16px;
    font-weight: 700;
  }
  .progress-number {
    font-size: 24px;
    font-weight: 500;
  }
  .progress-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    height: 60%;
    margin-top: 30px;
  }
}
.demo-progress {
  margin-left: -5px;
}
.demo-progress .el-progress--line {
  display: flex;
  max-width: 600px;
  margin-bottom: 15px;
}
.right1-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 15.6%;
  height: 120px;
  margin-right: 24px;
  color: var(--el-text-color-primary);
  cursor: pointer;
  background-color: var(--el-bg-color2);
  border-radius: 8px;
  opacity: 0.8;
  transition: all 0.3s;
}
.right1-itemShadow {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 15.6%;
  height: 120px;
  margin-right: 24px;
  color: var(--el-text-color-primary);
  background-color: var(--el-bg-color2);
  border-radius: 8px;
  box-shadow: 2px 2px 22px var(--el-shadow-color);
  opacity: 1;
  transform: translate(0, -5px);
}
</style>
